package command

import (
	"flag"
	"fmt"
	"strings"

	"github.com/mitchellh/cli"

	libp2p "github.com/tokentransfer/interfaces/p2p"

	"github.com/tokentransfer/node/account"
	"github.com/tokentransfer/node/config"
	"github.com/tokentransfer/node/util"

	"github.com/tokentransfer/consensus/p2p"
)

// InfoCommand is a Command implementation that queries a running
// Node agent for various debugging statistics for operators
type InfoCommand struct {
	Ui cli.Ui
}

var _ cli.Command = &InfoCommand{}

func (i *InfoCommand) Help() string {
	helpText := `
Usage: node info [options]
	Provides debugging information for operators
Options:
	-config		Path to a JSON file to read configuration from.
`
	return strings.TrimSpace(helpText)
}

func (i *InfoCommand) Run(args []string) int {
	var configFile string

	cmdFlags := flag.NewFlagSet("info", flag.ContinueOnError)
	cmdFlags.Usage = func() { i.Ui.Output(i.Help()) }
	cmdFlags.StringVar(&configFile, "config", "./config.json", "json file to read config from")
	if err := cmdFlags.Parse(args); err != nil {
		return 1
	}

	config, err := config.NewConfig(configFile)
	if err != nil {
		panic(err)
	}
	as := account.GetAccountService()

	if len(config.GetSecret()) == 0 {
		secret, err := i.Ui.AskSecret("The secret:")
		if err != nil {
			panic(err)
		}
		config.SetSecret(secret)
	}

	_, nodeKey, err := as.NewKeyFromSecret(config.GetSecret())
	if err != nil {
		panic(err)
	}
	nodeAccount, err := nodeKey.GetAddress()
	if err != nil {
		panic(err)
	}
	i.Ui.Output("节点地址: " + util.GetString(nodeAccount))

	if config.GetAddress() == "localhost" || config.GetAddress() == "127.0.0.1" {
		i.Ui.Warn("警告：配置文件中的address是p2p服务使用的IP地址，如果为localhost或127.0.0.1, 将不能联网，只能本地使用, 建议配置成本机IP")
		return 1
	}

	net := &p2p.Network{}
	err = net.Start(config, make(map[string]libp2p.MessageCallback))
	if err != nil {
		panic(err)
	}
	address := fmt.Sprintf("/ip4/%s/tcp/%d/p2p/%s", config.GetAddress(), config.GetPort(), config.GetNodeId())
	i.Ui.Output("P2P地址: " + address)

	rpcAddress := fmt.Sprintf("http://%s:%d/v1/jsonrpc", config.GetRPCAddress(), config.GetRPCPort())
	i.Ui.Output("RPC地址: " + rpcAddress)

	return 0
}

func (i *InfoCommand) Synopsis() string {
	return "Provides debugging information for operators"
}
